<template>
  <div class="forget-container">
    <div class="forget-box">
      <div class="forget-title">忘记密码！</div>
      <div class="en-title">forgot password!</div>
      <!-- 用户信息验证 -->
      <van-form validate-first>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field v-model.trim="phone" label="手机号" placeholder="请输入手机号" maxlength="11">
          <template #button>
            <van-button size="small" type="primary" color="#0C34BA" @click="getEmailValidatorCode" v-if="flag">发送验证码</van-button>
            <van-button size="small" type="primary" color="#0C34BA" disabled v-else>{{ timeCount }}s后重新发送</van-button>
          </template>
        </van-field>

        <!-- 验证码 -->
        <van-field label="验证码" v-model="code" placeholder="验证码(6位数字)" maxlength="6" />

        <!-- 通过 validator 进行函数校验 -->
        <van-field v-model.trim="password" :type="text" name="密码" label="密码" placeholder="密码(6-16位)" :right-icon="eye" @click-right-icon="toggleEye" maxlength="16" />
        <!-- 通过 validator 进行异步函数校验 -->
        <van-field :type="text" label="确认密码" v-model="newPassword" name="确认密码" placeholder="请再次输入密码" :right-icon="eye" @click-right-icon="toggleEye" />

        <div class="forgot">
          <span @click="$router.replace('/login')">已有账号，立即登录</span>
        </div>
        <div class="login-btn">
          <van-button class="register-btn" round block @click="onSubmit">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'forget-view',
  data() {
    return {
      eye: 'closed-eye',
      text: 'password',
      phone: '',
      password: '',
      newPassword: '',
      code: '',
      timeCount: 60,
      timer: null,
      flag: true,
      codePattern: /^\d{6}$/,
      pattern: /^1[3-9]\d{9}$/,
      pwdPattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/
    }
  },
  methods: {
    toggleEye() {
      if (this.eye === 'closed-eye') {
        this.eye = 'eye-o'
        this.text = 'text'
      } else {
        this.eye = 'closed-eye'
        this.text = 'password'
      }
    },
    async onSubmit() {
      // 手机号不能为空并且格式不能错误
      if (this.phone == '') {
        return Notify({
          type: '',
          message: '请输入手机号！'
        })
      }
      if (!this.pattern.test(this.phone)) {
        return Notify({
          type: 'danger',
          message: '手机号格式错误！'
        })
      }

      // 验证验证码是否正确
      if (this.code === '') {
        return Notify({
          type: 'danger',
          message: '请输入验证码！'
        })
      }
      if (!this.codePattern.test(this.code)) {
        return Notify({
          type: 'danger',
          message: '验证码为6位有效数字！'
        })
      }

      // 验证密码
      if (this.password === '') {
        return Notify({
          type: 'danger',
          message: '请输入密码！'
        })
      }
      if (!this.pwdPattern.test(this.password)) {
        return Notify({
          type: 'danger',
          message: '密码为6-16位数字字母组合！'
        })
      }

      // 再次确认密码
      if (this.newPassword === '') {
        return Notify({
          type: 'danger',
          message: '请再次确认密码！'
        })
      }
      if (!this.pwdPattern.test(this.newPassword)) {
        return Notify({
          type: 'danger',
          message: '密码为6-16位数字字母组合！'
        })
      }

      // 两次输入的密码必须一致
      if (this.password !== this.newPassword) {
        return Notify({
          type: 'danger',
          message: '两次输入的密码不一致！'
        })
      }

      this.$toast.loading({
        duration: 0,
        message: '加载中...',
        loadingType: 'spinner'
      })
      try {
        const data = await axios.post('/api/user/forget', {
          phone: this.phone,
          code: this.code,
          password: this.password,
          newPassword: this.newPassword
        })

        if (data.code === 0) {
          Notify({
            type: 'success',
            message: data.msg,
            duration: 500,
            onClose: () => {
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 发送验证码
    async getEmailValidatorCode() {
      // 手机号不能为空并且格式不能错误
      if (this.phone == '') {
        return Notify({
          type: 'danger',
          message: '请输入手机号！'
        })
      }
      if (!this.pattern.test(this.phone)) {
        return Notify({
          type: 'danger',
          message: '手机号格式错误！'
        })
      }
      this.$toast.loading({
        duration: 0,
        message: '加载中...',
        loadingType: 'spinner'
      })

      try {
        // 发起请求获取验证码
        const data = await axios.post('/api/getcode', {
          phone: this.phone
        })
        // 获取成功
        if (data.code === 0) {
          this.flag = false
          Notify({
            type: 'success',
            message: '验证码发送成功，请注意查收！',
            duration: 1000
          })
          this.timer = setInterval(() => {
            this.timeCount--
            if (this.timeCount <= 0) {
              clearInterval(this.timer)
              this.timeCount = 60
              this.flag = true
            }
          }, 1000)
        } else {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.forget-container {
  .forget-box {
    margin-top: 120px;

    .forget-title {
      line-height: 40px;
      font-size: 24px;
      font-weight: 700;
      padding: 0 10px;
    }

    .en-title {
      margin-top: 20px;
      color: #999;
      font-size: 18px;
      line-height: 21px;
      padding: 0 10px;
    }
    .van-form {
      margin-top: 20px;
      padding: 15px;

      .van-cell {
        padding: 10px 15px;
      }

      ::v-deep .van-field__label {
        width: 4.5em;
      }
    }
    .forgot {
      text-align: right;
      margin-top: 20px;

      span {
        color: #666;
        font-size: 12px;
        line-height: 16px;
      }
    }
    .login-btn {
      margin-top: 30px;

      .register-btn {
        background-color: #f92946;
        color: white;
        border: 1px solid #f92946;
      }
    }
  }

  ::v-deep .van-field--error .van-field__control,
  ::v-deep .van-field--error .van-field__control::placeholder {
    color: rgba(50, 50, 50, 0.5);
    -webkit-text-fill-color: currentColor;
  }
}
</style>
